package logic

import (
	"context"
	"message/internal/svc"
	"message/pb/message"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetMessageListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetMessageListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMessageListLogic {
	return &GetMessageListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// GetMessageList 获取消息列表
func (l *GetMessageListLogic) GetMessageList(in *message.MessageListRequest) (*message.MessageListResponse, error) {
	total, _, _, err := l.svcCtx.MessageAggregationModel.GetMessageCount(l.ctx, in.UserId, in.SenderId, in.ReceiverType, in.ReceiverId, in.Status)
	if err != nil {
		return nil, err
	}
	msgList, err := l.svcCtx.MessageAggregationModel.GetMessageList(l.ctx, in.SenderId, in.ReceiverType, in.ReceiverId, in.UserId, in.Status, in.LastMsgId, in.Limit)
	if err != nil {
		return nil, err
	}

	var data []*message.MessageInfo
	for _, msg := range msgList {
		data = append(data, &message.MessageInfo{
			Id:           msg.Id,
			SenderId:     msg.SenderId,
			ReceiverType: msg.ReceiverType,
			ReceiverId:   msg.ReceiverId,
			ContentType:  msg.ContentType,
			Content:      msg.Content,
			FileName:     msg.FileName,
			FileSize:     msg.FileSize,
			Status:       msg.Status,
			CreateAt:     msg.CreatedAt.Unix(),
		})
	}
	return &message.MessageListResponse{Total: total, Data: data}, nil
}
